<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Image;
use app\admin\model\Department;

use think\Db;
use think\Request;

/**
 * 机构
 */
class Institution extends Base
{
    public function _initialize() {
        parent::_initialize();

        $this->redirect = 'admin/institution/index';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'name' => [
                'label'     => '机构',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as $item) {
                $countDepartment = Department::where(['institutionId' => $item->id])->count();
                $item->countDepartment = $countDepartment;
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request) {
        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {
        $redirect = $this->redirect;
        return parent::addPost($request, $redirect);
    }

    public function edit(Request $request) {
        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){
        return parent::editPost($request, $redirect);
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        if($id){
            $department = Department::where(['institutionId' => $id])->select();
            if($department) {
                return $this->error('该机构有部门，请先去删除部门！');
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

    /**
     * 部门
     */
    public function department(Request $request){
        $id = $request->param('institutionId');

        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model('Department');

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = [
                'institutionId' => $param['id']
            ];

            if($param['search']['value']) {
                $filter = json_decode($param['search']['value'],true);
                if(isset($filter['cityId']) && $filter['cityId']){
                    $where['cityId'] = $filter['cityId'];
                }
                if(isset($filter['xianId']) && $filter['xianId']){
                    $where['xianId'] = $filter['xianId'];
                }
                if(isset($filter['townId']) && $filter['townId']){
                    $where['townId'] = $filter['townId'];
                }
                if(isset($filter['villageId']) && $filter['villageId']){
                    $where['villageId'] = $filter['villageId'];
                }

                if(isset($filter['name']) && $filter['name']){
                    $where['name'] = ['like', '%'.$filter['name'].'%'];
                }
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();

            foreach ($list as $item) {
                $item['institution'] = \app\admin\model\Institution::where(['id' => $item['institutionId']])->value('name');
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        $this->searchFields = [
            'name' => [
                'label'     => '部门',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        $this->assign('institutionId', $id);

        return $this->view->fetch('department/list', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 添加部门
     */
    public function addDepartment(Request $request){
        $institutionId = $request->param('institutionId');
        $model = model($this->model);
        $institutionInfo = $model->where('id', $institutionId)->find();
        if(!$institutionInfo){
            $this->error();
        }

        $this->model = 'Department';
        $this->addView = 'department/add';

        $this->assign('area', $this->getArea($institutionInfo));
        $this->assign('institution', $institutionInfo);

        return parent::add($request);
    }

    /**
     * 编辑部门
     */
    public function editDepartment(Request $request){
        $institutionId = $request->param('institutionId');
        $model = model($this->model);
        $institutionInfo = $model->where('id', $institutionId)->find();
        if(!$institutionInfo){
            $this->error();
        }

        $this->model = 'Department';
        $this->editView = 'department/edit';

        $this->assign('area', $this->getArea($institutionInfo));
        $this->assign('institution', $institutionInfo);

        //return parent::edit($request);
        $id = $request->param('id');
        $info = model('Department')->find($id);

        if(!$info){
            return $this->error('error !');
        }

        return $this->view->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * 保存部门
     */
    public function saveDepartment(Request $request){
        $model = model('Department');
        if ($request->isPost()) {
            $data = $request->param();
            if(isset($data['id']) && $data['id']){
                $data['updateDate'] = time();
                $data['updateOper'] = $this->admin->id;

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_update($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '更新了一条部门数据。';
                    Common::adminLog($request, $logInfo);

                    return json(['code' => 1, 'msg' => '保存成功！', 'id' => $data['id'], 'url' => url('admin/institution/department', ['institutionId' => $data['institutionId']])]);
                } else {
                    return json(['code' => 0, 'msg' => $model->getError()]);
                }
            }

            // Insert data
            $data['id'] = Helper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;

            $result = $model->save($data);

            if($result !== false) {
                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条部门数据。';
                Common::adminLog($request, $logInfo);

                return json(['code' => 1, 'msg' => '添加成功！', 'id' => $data['id'], 'url' => url('admin/institution/department', ['institutionId' => $data['institutionId']])]);
            } else {
                return json(['code' => 0, 'msg' => $model->getError()]);
            }
        } else {
            return $this->error('');
        }
    }

    /**
     * 删除部门
     */
    public function delDepartment(){
        $model = model('Department');

        $request = $this->request;
        $id = $request->param('id');

        // 删除一条
        $info = $model->find(['id', $id]);
        if(!$info){
            return $this->error('该数据不存在');
        }
        $result = $model->where('id', $id)->delete();

        if($result !== false){
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条部门数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', url('admin/institution/department', ['institutionId' => $info->institutionId]));
        }else{
            return $this->error('删除失败！', url('admin/institution/department', ['institutionId' => $info->institutionId]));
        }
    }

}
